package cn.shenlong.job;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.shenlong.common.Constants;
import cn.shenlong.portal.domain.Channel;
import cn.shenlong.portal.domain.Content;
import cn.shenlong.portal.service.ChannelService;
import cn.shenlong.portal.service.ContentService;
import cn.shenlong.util.FileUtil;

/**
 * 内容模块任务
 * 
 */
@Component("fileJob")
public class FileJob implements Serializable {

	private static final long serialVersionUID = -6499166736604808045L;

	@Autowired
	private ContentService contentService;

	@Autowired
	private ChannelService channelService;

	private static Logger logger = Logger.getLogger(FileJob.class);

	/**
	 * 同步文件 把多余的文件删除
	 */
	@SuppressWarnings("unchecked")
	public void syncFile() {
		List<String> urlList = new ArrayList<String>();// 用来已经上传资源的路径
		List<String> dbUrlList = new ArrayList<String>();// 用来已经上传资源的路径
		try {

			String dir = Constants.APPLICATION_URL;
			List<File> FileList = new ArrayList<File>();
			// 1.注册 已经存在的资源的路径
			FileList.addAll(FileUtil.getAllFiles(dir
					+ Constants.UEDITOR_IMG_URI));
			FileList.addAll(FileUtil.getAllFiles(dir
					+ Constants.CHANNEL_IMG_URI));
			FileList.addAll(FileUtil.getAllFiles(dir
					+ Constants.CONTENT_IMG_URI));
			// 友情链接等代码稳定后再做添加
			// FileList.addAll(FileUtil.getAllFiles(Constants.LINK_IMG_URI));
			for (File f : FileList) {
				urlList.add(f.getPath());
			}

			// 2.注册 数据库中存在的有效资源路径，即排除（http://开头的路径和数据有效标准位为0）的数据
			// 注册内容相关文件
			List<Content> list = (List<Content>) contentService.findContents(
					null, null, null, null).getList();
			for (Content content : list) {
				if (!StringUtil.isBlank(content.getTitleImage())) {
					dbUrlList.add(new File(dir + content.getTitleImage())
							.getPath());
				}
				if (!StringUtil.isBlank(content.getTypeImage())) {
					dbUrlList.add(new File(dir + content.getTypeImage())
							.getPath());
				}
				if (!StringUtil.isBlank(content.getTxt())) {
					Document doc = Jsoup.parse(content.getTxt());
					Elements imgs = doc.getElementsByTag("img");
					for (Element img : imgs) {
						try {
							String linksHref = img.attr("src");
							if (!StringUtil.isBlank(linksHref)
									&& linksHref.indexOf("http") != 0) {
								File f = new File(dir + linksHref);
								dbUrlList.add(f.getPath());
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
			// 注册栏目相关文件
			List<Channel> channelList = (List<Channel>) channelService
					.findPageListByCriteria(null, null, null).getList();
			for (Channel channel : channelList) {
				if (!StringUtil.isBlank(channel.getTxt())) {
					Document doc = Jsoup.parse(channel.getTxt());
					Elements imgs = doc.getElementsByTag("img");
					for (Element img : imgs) {
						try {
							String linksHref = img.attr("src");
							if (!StringUtil.isBlank(linksHref)
									&& linksHref.indexOf("http") != 0) {
								File f = new File(dir + linksHref);
								dbUrlList.add(f.getPath());
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}

			// 3.比较出不存在数据库中的资源，进行删除操作
			for (String url : urlList) {
				if (!dbUrlList.contains(url)) {
					FileUtil.deleteFile(url);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			urlList.clear();
			dbUrlList.clear();
			logger.error("fileJob syncFile:{}", e);
		}

	}
}
